<template>
    <div class="project-import">
      <el-card class="import-card">
        <template #header>
          <div class="card-header">
            <span>项目导入</span>
            <el-button type="primary" @click="downloadTemplate">
              <el-icon><download /></el-icon>
              下载导入模板
            </el-button>
          </div>
        </template>
        
        <div class="import-container">
          <el-upload
            class="upload-area"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept=".zip,.rar,.xlsx,.xls"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .zip/.rar 格式的项目文件，或 .xlsx/.xls 格式的Excel文件
              </div>
            </template>
          </el-upload>
  
          <div v-if="fileList.length > 0" class="upload-actions">
            <el-button type="primary" @click="handleUpload" :loading="uploading">
              开始上传
            </el-button>
            <el-button @click="handleClear">清除文件</el-button>
          </div>
  
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-bar">
            <el-progress 
              :percentage="uploadProgress"
              :status="uploadStatus"
            />
          </div>
  
          <div v-if="errorMessage" class="error-message">
            <el-alert
              :title="errorMessage"
              type="error"
              show-icon
            />
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { UploadFilled, Download } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  
  const fileList = ref([])
  const uploadProgress = ref(0)
  const uploadStatus = ref('')
  const errorMessage = ref('')
  const uploading = ref(false)
  
  const beforeUpload = (file) => {
    const isValidType = file.type === 'application/zip' || 
                       file.type === 'application/x-rar-compressed' ||
                       file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                       file.type === 'application/vnd.ms-excel' ||
                       file.name.endsWith('.zip') ||
                       file.name.endsWith('.rar') ||
                       file.name.endsWith('.xlsx') ||
                       file.name.endsWith('.xls')
    
    if (!isValidType) {
      ElMessage.error('只能上传 ZIP/RAR 格式的项目文件或 Excel 文件！')
      return false
    }
    
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isLt100M) {
      ElMessage.error('文件大小不能超过 100MB！')
      return false
    }
    
    return true
  }
  
  const handleFileChange = (file) => {
    fileList.value = [file]
    errorMessage.value = ''
  }
  
  const handleClear = () => {
    fileList.value = []
    uploadProgress.value = 0
    uploadStatus.value = ''
    errorMessage.value = ''
  }
  
  const handleUpload = async () => {
    if (fileList.value.length === 0) {
      ElMessage.warning('请先选择要上传的文件')
      return
    }
  
    const file = fileList.value[0].raw
    const formData = new FormData()
    formData.append('file', file)
  
    uploading.value = true
    uploadProgress.value = 0
    uploadStatus.value = ''
    errorMessage.value = ''
  
    try {
      const response = await axios.post('/api/upper_ftpmachiningcenter/FileUploadProject', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        }
      })
  
      uploadProgress.value = 100
      uploadStatus.value = 'success'
      ElMessage.success('项目导入成功！')
      handleClear()
    } catch (error) {
      uploadStatus.value = 'exception'
      errorMessage.value = error.response?.data?.message || '导入失败，请重试'
      ElMessage.error('项目导入失败！')
    } finally {
      uploading.value = false
    }
  }
  
  const downloadTemplate = async () => {
    try {
      const response = await axios.get('/api/upper_ftpmachiningcenter/template', {
        responseType: 'blob'
      })
      
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', '项目导入模板.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('模板下载成功')
    } catch (error) {
      ElMessage.error('模板下载失败：' + (error.response?.data?.message || error.message))
    }
  }
  </script>
  
  <style scoped>
  .project-import {
    padding: 20px;
  }
  
  .import-card {
    max-width: 600px;
    margin: 0 auto;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .import-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .upload-area {
    width: 100%;
  }
  
  .upload-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
    justify-content: center;
  }
  
  .progress-bar {
    margin-top: 20px;
  }
  
  .error-message {
    margin-top: 20px;
  }
  
  .el-upload__tip {
    color: #909399;
    font-size: 14px;
    margin-top: 10px;
  }
  </style> 